// 导入模块

import { usetokenStore } from '@/stores/token'
import HttpRequest, { type HttpMethod, type HttpRequestConfig } from 'luch-request'

export const service = new HttpRequest({
  baseURL: 'https://consult-api.itheima.net',
  timeout: 15 * 1000,
  custom: {
    loading: true,
  },
})
// 接口白名单
const whiteList = ['/code', '/login', '/login/password']
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      uni.showLoading({ title: '正在加载...', mask: true })
    }
    const store = usetokenStore()
    if (store.token && config.url && !whiteList.includes(config.url)) {
      config.header!.Authorization = `Bearer ${store.token}`
    }
    // console.log('config', config)
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 隐藏加载状态提示
    uni.hideLoading()

    if (response.data.code !== 10000) {
      uni.showToast({
        title: response.data.message,
        icon: 'none',
      })
      return Promise.reject(response.data)
    }
    return response.data
  },
  (err) => {
    // 隐藏加载状态提示
    uni.hideLoading()
    const store = usetokenStore()
    if (err.data.code === 401) {
      uni.showToast({
        title: err.data.message,
        icon: 'none',
      })
      store.removeToken()
      uni.redirectTo({ url: '/pages/login/login' })
    }
    return Promise.reject(err)
  }
)

// 封装请求方法
// 服务端响应数据结构
export interface ServiceResponse<T> {
  code: number
  message: string
  data: T
}
const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  submitData?: object,
  config?: HttpRequestConfig
) => {
  return service.request<T, ServiceResponse<T>>({
    url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    ...config,
  })
}
export { request }
